package net.imagine.backend.mockrmi.remote.provider.netty.server;

import java.net.InetSocketAddress;

import net.imagine.backend.mockrmi.remote.protocol.ResponseBean;
import net.imagine.backend.mockrmi.util.MockRmiUtils;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import org.jboss.netty.channel.WriteCompletionEvent;

/**
 * Netty实现的服务端IO处理类
 * 
 * @author wuqh
 * @see SimpleChannelUpstreamHandler
 * @see MockRmiUtils#handlerMessage(Object, InetSocketAddress)
 * */
public class NettyServerIoHandler extends SimpleChannelUpstreamHandler {
	private static final Log logger = LogFactory.getLog(NettyServerIoHandler.class);

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
		logger.error("server occurred an unexpected excpetion", e.getCause());
	}

	@Override
	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
		logger.debug("Server:message received");
		InetSocketAddress addr = (InetSocketAddress) ctx.getChannel().getLocalAddress();
		ResponseBean response = MockRmiUtils.handlerMessage(e.getMessage(), addr);
		ctx.getChannel().write(response);
	}

	@Override
	public void writeComplete(ChannelHandlerContext ctx, WriteCompletionEvent e) throws Exception {
		logger.debug("Server:channel sended");
	}

	@Override
	public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
		logger.debug("Server:channel closed");
	}

}
